package com.samoiloff.ui.scroll.resize.controller {
	import com.samoiloff.ui.scroll.resize.model.ResizeScrollModel;
	import com.samoiloff.ui.scroll.resize.view.ResizeScrollView;

	import flash.events.Event;

	/**
	 * @author Samoiloff
	 */
	public class ResizeScrollModelController extends BaseResizeScrollController {
		
		private var _scrollView: ResizeScrollView;
		private var _scrollModel:ResizeScrollModel;
		
		//private var _viewContentHeight: Number;
		//private var _modelContentHeight: Number;
		
		public function ResizeScrollModelController(model: ResizeScrollModel) {
			super(model);
			
			_scrollModel = model;
			_scrollView = model.view;
			
			_model.addEventListener(ResizeScrollModel.HEIGHT_CHANGED, onHeightChanged);
			_model.addEventListener(ResizeScrollModel.MAX_SCROLL_POSITION_CHANGED, onMaxScrollPositionChanged);
			_model.addEventListener(ResizeScrollModel.SCROLL_POSITION_CHANGED, onScrollPositionChanged);
			
			
			
			onResize();
		}

		private function onScrollPositionChanged(event: Event): void {
			onScroll();
		}

		private function onMaxScrollPositionChanged(event: Event): void {
			onResize();
		}

		private function onHeightChanged(e:Event): void {
			onResize();
		}

		private function onResize(): void {
			if (_scrollModel.maxScrollPosition) {
				_scrollView.bg.height = _scrollModel.height;
				_scrollView.downArrow.mc.y = _scrollModel.height;
				
				_scrollView.vmKoeff = getViewContentHeight()/getModelContentHeight();  
				
				_scrollView.slider.height = _scrollModel.height * _scrollView.vmKoeff;
				onScroll();
			} else {
				
			}
		}
		
		private function onScroll():void {
			var y:Number = _scrollModel.scrollPosition*_scrollView.vmKoeff;
			_scrollView.slider.mc.y = _scrollView.upArrow.mc.height + y;
			
			_scrollView.upArrow.enabled = _scrollModel.scrollPosition > 0;
			_scrollView.downArrow.enabled = _scrollModel.scrollPosition < _scrollModel.maxScrollPosition;
		}

		private function getViewContentHeight():Number {
			return _scrollView.bg.height - _scrollView.upArrow.mc.height - _scrollView.downArrow.mc.height;
		}
		
		private function getModelContentHeight():Number {
			return _scrollModel.height + _scrollModel.maxScrollPosition;
		}
	}
}
